# coding=utf8
import time
import requests

from support_services.constants import PROXIES_POOL
from support_services.constants import PROXIES_POOL_KEY
from support_services.constants import PROXIES_DAILIYUN_URL
from support_services.constants import PROXIES_DAILITUN_MIN_COUNT

from tools.logger import Logger
from tools.timing import timing, check_timing
from tools.timing_handler import main as main_timing
from tools.redis_handler import RedisHandler


class SupportProxies(object):
    def __init__(self, error_back=None, **kwargs):
        self.error_back = error_back

    def run(self, logger):
        # 每10秒钟执行一次
        @timing("", interval=5, logger=logger)
        def exec_proxy_pool(*args, **kwargs):
            self.execute(*args, **kwargs)

        main_timing(logger, exec_proxy_pool, *(), *{"logger": logger})

    def execute(self, *args, **kwargs):
        logger = kwargs["logger"]

        try:
            redishandler = RedisHandler(startup_node=PROXIES_POOL["startup_node"])

            # 获取代理
            proxies = self.get_proxies()
            # 获取池中全部代理
            members = redishandler.smembers(PROXIES_POOL_KEY)

            # 添加当前页代理到池中
            redishandler.sadd(PROXIES_POOL_KEY, *proxies)

            # 删除池中失效代理
            for memberi in members:
                if memberi in proxies:
                    continue
                redishandler.srem(PROXIES_POOL_KEY, memberi)

            # 获取池中全部代理
            members = redishandler.smembers(PROXIES_POOL_KEY)
            logger.info("代理池已更新。现有{}个。{}。".format(len(members), members))

            # 每次设置本批代理池有效期30秒
            redishandler.expire(PROXIES_POOL_KEY, 30)

            # # 随机获取一个使用
            # value = redishandler.srandmember(PROXY_KEY)
            # print(value)
        except Exception as error:
            self.error_back.report("代理池在使用过程中报错，等待下次调用，{}".format(error))

    def get_proxies(self):
        count = 0

        while 1:
            count += 1
            message = ""

            try:
                r = requests.get(PROXIES_DAILIYUN_URL)
                proxies = r.content.splitlines()
                if proxies:
                    if len(proxies) < PROXIES_DAILITUN_MIN_COUNT:
                        self.error_back.report("代理云的代理变少了，{}，{}。".format(len(proxies), r.content))
                    return proxies
                else:
                    message = "空，{}。".format(r.content)

            except Exception as error:
                message = "报错，{}。".format(error)

            if count > 5:
                self.error_back.report("代理云的代理连续获取失败{}次，{}。".format(count, message))

            time.sleep(2)
